// 内存监控和泄漏检测服务

export interface MemoryInfo {
  usedJSHeapSize: number;
  totalJSHeapSize: number;
  jsHeapSizeLimit: number;
  timestamp: number;
}

export interface MemoryLeakReport {
  type: 'event-listener' | 'timer' | 'dom-node' | 'closure' | 'component-state' | 'custom';
  description: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
  location?: string;
  suggestions: string[];
  details?: any;
}

export interface PerformanceReport {
  memoryInfo: MemoryInfo;
  leaks: MemoryLeakReport[];
  recommendations: string[];
  score: number; // 0-100
  timestamp: number;
}

// 内存使用历史记录
export interface MemoryHistoryPoint {
  timestamp: number;
  memoryInfo: MemoryInfo;
  activeComponents: number;
  eventListeners: number;
  timers: number;
}

/**
 * 内存监控服务
 */
export class MemoryMonitorService {
  private isMonitoring = false;
  private monitoringInterval?: NodeJS.Timeout;
  private memoryHistory: MemoryHistoryPoint[] = [];
  private maxHistoryLength = 100;
  private listeners: Array<(info: MemoryInfo) => void> = [];
  
  // 内存泄漏检测器
  private eventListenerTracker = new Map<string, number>();
  private timerTracker = new Set<NodeJS.Timeout>();
  private componentTracker = new Map<string, number>();
  private domNodeTracker = new WeakSet<Node>();
  
  // 警告阈值
  private thresholds = {
    memoryUsage: 500 * 1024 * 1024, // 500MB
    memoryGrowthRate: 10 * 1024 * 1024, // 10MB/min
    eventListenerCount: 1000,
    timerCount: 100,
    componentCount: 500
  };

  /**
   * 开始监控
   */
  startMonitoring(intervalMs: number = 5000): void {
    if (this.isMonitoring) {
      console.warn('[内存监控] 监控已在运行中');
      return;
    }

    console.log('[内存监控] 开始内存监控');
    this.isMonitoring = true;

    this.monitoringInterval = setInterval(() => {
      this.collectMemoryInfo();
    }, intervalMs);

    // 立即收集一次数据
    this.collectMemoryInfo();
  }

  /**
   * 停止监控
   */
  stopMonitoring(): void {
    if (!this.isMonitoring) {
      return;
    }

    console.log('[内存监控] 停止内存监控');
    this.isMonitoring = false;

    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval);
      this.monitoringInterval = undefined;
    }
  }

  /**
   * 收集内存信息
   */
  private collectMemoryInfo(): void {
    const memoryInfo = this.getMemoryUsage();
    const historyPoint: MemoryHistoryPoint = {
      timestamp: Date.now(),
      memoryInfo,
      activeComponents: this.componentTracker.size,
      eventListeners: Array.from(this.eventListenerTracker.values()).reduce((sum, count) => sum + count, 0),
      timers: this.timerTracker.size
    };

    // 添加到历史记录
    this.memoryHistory.push(historyPoint);
    if (this.memoryHistory.length > this.maxHistoryLength) {
      this.memoryHistory.shift();
    }

    // 通知监听器
    this.listeners.forEach(listener => {
      try {
        listener(memoryInfo);
      } catch (error) {
        console.error('[内存监控] 监听器回调失败:', error);
      }
    });

    // 检查是否需要警告
    this.checkMemoryWarnings(historyPoint);
  }

  /**
   * 获取当前内存使用情况
   */
  getMemoryUsage(): MemoryInfo {
    if ('memory' in performance) {
      const memory = (performance as any).memory;
      return {
        usedJSHeapSize: memory.usedJSHeapSize,
        totalJSHeapSize: memory.totalJSHeapSize,
        jsHeapSizeLimit: memory.jsHeapSizeLimit,
        timestamp: Date.now()
      };
    }

    // 降级方案：使用估算值
    return {
      usedJSHeapSize: 0,
      totalJSHeapSize: 0,
      jsHeapSizeLimit: 0,
      timestamp: Date.now()
    };
  }

  /**
   * 检测内存泄漏
   */
  detectLeaks(): MemoryLeakReport[] {
    const leaks: MemoryLeakReport[] = [];

    // 检测事件监听器泄漏
    leaks.push(...this.detectEventListenerLeaks());

    // 检测定时器泄漏
    leaks.push(...this.detectTimerLeaks());

    // 检测组件状态泄漏
    leaks.push(...this.detectComponentLeaks());

    // 检测内存增长趋势
    leaks.push(...this.detectMemoryGrowthLeaks());

    return leaks;
  }

  /**
   * 检测事件监听器泄漏
   */
  private detectEventListenerLeaks(): MemoryLeakReport[] {
    const leaks: MemoryLeakReport[] = [];
    const totalListeners = Array.from(this.eventListenerTracker.values()).reduce((sum, count) => sum + count, 0);

    if (totalListeners > this.thresholds.eventListenerCount) {
      leaks.push({
        type: 'event-listener',
        description: `检测到过多的事件监听器: ${totalListeners}个`,
        severity: totalListeners > this.thresholds.eventListenerCount * 2 ? 'critical' : 'high',
        suggestions: [
          '检查组件卸载时是否正确移除事件监听器',
          '使用 useEffect 清理函数移除监听器',
          '避免在渲染过程中重复添加监听器'
        ],
        details: Object.fromEntries(this.eventListenerTracker)
      });
    }

    return leaks;
  }

  /**
   * 检测定时器泄漏
   */
  private detectTimerLeaks(): MemoryLeakReport[] {
    const leaks: MemoryLeakReport[] = [];
    const timerCount = this.timerTracker.size;

    if (timerCount > this.thresholds.timerCount) {
      leaks.push({
        type: 'timer',
        description: `检测到过多的活跃定时器: ${timerCount}个`,
        severity: timerCount > this.thresholds.timerCount * 2 ? 'critical' : 'high',
        suggestions: [
          '确保组件卸载时清除所有定时器',
          '使用 useEffect 清理函数清除定时器',
          '避免创建不必要的定时器'
        ],
        details: { activeTimers: timerCount }
      });
    }

    return leaks;
  }

  /**
   * 检测组件泄漏
   */
  private detectComponentLeaks(): MemoryLeakReport[] {
    const leaks: MemoryLeakReport[] = [];
    const componentCount = this.componentTracker.size;

    if (componentCount > this.thresholds.componentCount) {
      leaks.push({
        type: 'component-state',
        description: `检测到过多的活跃组件: ${componentCount}个`,
        severity: 'medium',
        suggestions: [
          '检查组件是否正确卸载',
          '避免创建过多的组件实例',
          '使用虚拟列表等优化技术'
        ],
        details: Object.fromEntries(this.componentTracker)
      });
    }

    return leaks;
  }

  /**
   * 检测内存增长趋势泄漏
   */
  private detectMemoryGrowthLeaks(): MemoryLeakReport[] {
    const leaks: MemoryLeakReport[] = [];
    
    if (this.memoryHistory.length < 5) {
      return leaks;
    }

    // 计算内存增长率
    const recent = this.memoryHistory.slice(-5);
    const first = recent[0];
    const last = recent[recent.length - 1];
    const timeDiff = (last.timestamp - first.timestamp) / 1000 / 60; // 分钟
    const memoryDiff = last.memoryInfo.usedJSHeapSize - first.memoryInfo.usedJSHeapSize;
    const growthRate = memoryDiff / timeDiff; // bytes/min

    if (growthRate > this.thresholds.memoryGrowthRate) {
      leaks.push({
        type: 'custom',
        description: `检测到持续的内存增长: ${(growthRate / 1024 / 1024).toFixed(2)}MB/分钟`,
        severity: growthRate > this.thresholds.memoryGrowthRate * 2 ? 'critical' : 'high',
        suggestions: [
          '检查是否存在内存泄漏',
          '分析内存快照找出泄漏源',
          '优化数据结构和算法',
          '实施垃圾回收策略'
        ],
        details: {
          growthRateMBPerMin: (growthRate / 1024 / 1024).toFixed(2),
          timePeriodMin: timeDiff.toFixed(1),
          memoryIncreaseMB: (memoryDiff / 1024 / 1024).toFixed(2)
        }
      });
    }

    return leaks;
  }

  /**
   * 检查内存警告
   */
  private checkMemoryWarnings(historyPoint: MemoryHistoryPoint): void {
    const { memoryInfo } = historyPoint;
    
    // 内存使用量警告
    if (memoryInfo.usedJSHeapSize > this.thresholds.memoryUsage) {
      console.warn('[内存监控] 内存使用量过高:', {
        current: `${(memoryInfo.usedJSHeapSize / 1024 / 1024).toFixed(2)}MB`,
        threshold: `${(this.thresholds.memoryUsage / 1024 / 1024).toFixed(2)}MB`
      });
    }

    // 内存使用率警告
    const usageRate = memoryInfo.usedJSHeapSize / memoryInfo.totalJSHeapSize;
    if (usageRate > 0.8) {
      console.warn('[内存监控] 内存使用率过高:', `${(usageRate * 100).toFixed(1)}%`);
    }
  }

  /**
   * 生成性能报告
   */
  generateReport(): PerformanceReport {
    const memoryInfo = this.getMemoryUsage();
    const leaks = this.detectLeaks();
    const recommendations = this.generateRecommendations(leaks);
    const score = this.calculatePerformanceScore(memoryInfo, leaks);

    return {
      memoryInfo,
      leaks,
      recommendations,
      score,
      timestamp: Date.now()
    };
  }

  /**
   * 生成优化建议
   */
  private generateRecommendations(leaks: MemoryLeakReport[]): string[] {
    const recommendations: string[] = [];
    
    if (leaks.length === 0) {
      recommendations.push('内存使用情况良好，无明显泄漏');
    } else {
      recommendations.push('发现内存泄漏问题，建议立即修复');
      
      if (leaks.some(leak => leak.type === 'event-listener')) {
        recommendations.push('优化事件监听器管理，确保正确清理');
      }
      
      if (leaks.some(leak => leak.type === 'timer')) {
        recommendations.push('检查定时器使用，避免忘记清理');
      }
      
      if (leaks.some(leak => leak.type === 'component-state')) {
        recommendations.push('优化组件生命周期管理');
      }
    }

    return recommendations;
  }

  /**
   * 计算性能分数
   */
  private calculatePerformanceScore(memoryInfo: MemoryInfo, leaks: MemoryLeakReport[]): number {
    let score = 100;

    // 内存使用量扣分
    const memoryUsageMB = memoryInfo.usedJSHeapSize / 1024 / 1024;
    if (memoryUsageMB > 200) {
      score -= Math.min(30, (memoryUsageMB - 200) / 10);
    }

    // 泄漏扣分
    leaks.forEach(leak => {
      switch (leak.severity) {
        case 'critical':
          score -= 25;
          break;
        case 'high':
          score -= 15;
          break;
        case 'medium':
          score -= 10;
          break;
        case 'low':
          score -= 5;
          break;
      }
    });

    return Math.max(0, Math.round(score));
  }

  /**
   * 添加内存信息监听器
   */
  addListener(listener: (info: MemoryInfo) => void): void {
    this.listeners.push(listener);
  }

  /**
   * 移除内存信息监听器
   */
  removeListener(listener: (info: MemoryInfo) => void): void {
    const index = this.listeners.indexOf(listener);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  /**
   * 获取内存历史记录
   */
  getMemoryHistory(): MemoryHistoryPoint[] {
    return [...this.memoryHistory];
  }

  /**
   * 注册事件监听器
   */
  trackEventListener(element: string, event: string): void {
    const key = `${element}:${event}`;
    const current = this.eventListenerTracker.get(key) || 0;
    this.eventListenerTracker.set(key, current + 1);
  }

  /**
   * 注销事件监听器
   */
  untrackEventListener(element: string, event: string): void {
    const key = `${element}:${event}`;
    const current = this.eventListenerTracker.get(key) || 0;
    if (current <= 1) {
      this.eventListenerTracker.delete(key);
    } else {
      this.eventListenerTracker.set(key, current - 1);
    }
  }

  /**
   * 注册定时器
   */
  trackTimer(timer: NodeJS.Timeout): void {
    this.timerTracker.add(timer);
  }

  /**
   * 注销定时器
   */
  untrackTimer(timer: NodeJS.Timeout): void {
    this.timerTracker.delete(timer);
  }

  /**
   * 注册组件
   */
  trackComponent(componentName: string): void {
    const current = this.componentTracker.get(componentName) || 0;
    this.componentTracker.set(componentName, current + 1);
  }

  /**
   * 注销组件
   */
  untrackComponent(componentName: string): void {
    const current = this.componentTracker.get(componentName) || 0;
    if (current <= 1) {
      this.componentTracker.delete(componentName);
    } else {
      this.componentTracker.set(componentName, current - 1);
    }
  }

  /**
   * 强制垃圾回收（仅在支持的环境中）
   */
  forceGarbageCollection(): void {
    if ('gc' in window && typeof (window as any).gc === 'function') {
      console.log('[内存监控] 强制垃圾回收');
      (window as any).gc();
    } else {
      console.warn('[内存监控] 当前环境不支持强制垃圾回收');
    }
  }

  /**
   * 清理所有追踪数据
   */
  clearAllTracking(): void {
    this.eventListenerTracker.clear();
    this.timerTracker.clear();
    this.componentTracker.clear();
    this.memoryHistory = [];
    console.log('[内存监控] 所有追踪数据已清理');
  }
}

// 全局内存监控服务实例
export const memoryMonitorService = new MemoryMonitorService();